package com.bnzjy.srb.sms.controller.api;

import com.bnzjy.common.exception.Assert;
import com.bnzjy.common.result.R;
import com.bnzjy.common.result.ResponseEnum;
import com.bnzjy.common.util.RandomUtils;
import com.bnzjy.srb.sms.component.SmsComponent;
import com.bnzjy.srb.sms.feign.CoreUserInfoFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin //跨域
@Slf4j
public class SmsSendController {
    
    @Resource
    SmsComponent smsComponent;
    
    @Resource
    RedisTemplate redisTemplate;
    
    @Resource
    CoreUserInfoFeign coreUserInfoFeign;
    
    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable String mobile) {
    
        // 手机号是否被注册过
        boolean result = coreUserInfoFeign.checkMobile(mobile);
        System.out.println("手机号result=" + result);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);
        
        // 生成验证码
        String code = RandomUtils.getFourBitRandom();
        // 组装短信模板参数
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        // 发送短信
        smsComponent.sendSmsCode(mobile, code, param);
        
        // 将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:srb:code:" + mobile, code, 5, TimeUnit.MINUTES);
        
        return R.ok().message("验证码发送成功");
    }
}
